package com.qipay.sp.excutor.ruyi;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.DateUtils;
import com.qipay.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class RuyiAliNativeExcutor extends AbstractExcutor {

    private final static String API_URL="api_url";
    @Autowired
    OrderService orderService;


    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("tradeNo",order.getTradeNo());
        apiParams.put("amount", new BigDecimal(order.getAmount()).divide(new BigDecimal("100")).toString());
        apiParams.put("applyDate", DateUtils.sdf.format(new Date()));
        apiParams.put("memberId",order.getCpId());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        Object apiUrl = getVal(spconfig, API_URL);
        Object merchantId = getVal(spconfig, "merchantId");//商户uid
        Object notifyUrl= getVal(spconfig, "notify_url");
        Object key= getVal(spconfig, "key");

        params.put("merchantId",merchantId);
        params.put("notifyUrl",notifyUrl);

        String sign = MD5Util.getSign(params,key.toString()).toLowerCase();
        params.put("sign",sign);

        String result = http(apiUrl.toString(),params);

        Order order = orderService.getByTradeNo(params.get("tradeNo").toString());

        Map<String, Object> resultMap = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(result);

        if("1".equals(jsonObject.getString("code"))){
            String codeUrl = jsonObject.getString("data");
            resultMap.put("status", ApiStatusEnum.OK.getCode());
            resultMap.put("pay_info", codeUrl);
            order.setState(OrderStateEnum.WAITING.getType());
        }else {
            resultMap.put("status", "1");
            resultMap.put("message", jsonObject.getString("info"));
            order.setState(OrderStateEnum.REQERROR.getType());
        }
        orderService.update(order);
        return resultMap;
    }

}
